<template>
  <div>
    <!--操作 -->
    <!-- <button-area :style="{ paddingLeft: '80px' }">
       <AjaxButton size="small" type="danger" :click="removeHandler">提报</AjaxButton>
      <AjaxButton size="small" type="danger" :click="removeHandler">VIN检验</AjaxButton>
      <AjaxButton size="small" type="danger" :click="removeHandler">获取置换政策</AjaxButton>
      <AjaxButton size="small" type="danger" :click="removeHandler">处理重审单</AjaxButton>
      <AjaxButton size="small" type="danger" :click="removeHandler">附件信息</AjaxButton>
      <AjaxButton size="small" type="danger" :click="removeHandler">审核记录</AjaxButton>
    </button-area>-->
    <!-- <div> -->
    <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="110" :formType="type" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <!-- </div> -->
    <div class="main_left">
      <LazyLoadTab v-model="activeName" :tabMenus="menus" />
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">关 闭</el-button>
      <AjaxButton v-if="type !== 'detailed'" type="primary" :click="saveDialog">保 存</AjaxButton>
      <BaseDialog :visible.sync="lincenseSearchDialog" title="底盘号选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <!-- <selectLicense @saveDialog="getSelectLicense" @closeDialog="lincenseSearchDialog = false" /> -->
      </BaseDialog>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import { getUser } from '@/assets/js/auth';
import dictCode from '@/utils/dictCode';
import { getGsdjSelect } from '@/api/repair/repairReception/customer';
import { searchRoleByCode } from '@/api/common/empSelect/index';
import { getModelAllListOEM } from '@/api/common/cars/brandcarsModels';
import { getAllUser } from '@/api/finance/repairFinance/closeBalance';
import { getEstimateData, getLabourData, getPartData, saveEstimate, getSeries } from '@/api/repair/estimateExtension';
import { getseriessdictList, getmodelsdictList } from '@/api/repair/repairReception/evaluation/index';
// import { addMaintain, updateMaintain } from '@/api/claimManagement/business/repair';
import moment from 'moment';
// import selectLicense from '@/pages/repair/repairReception/evaluation/LicenseSearchHelp'; /* 表选牌照号 */
// import selectCPDM from './selectCPDM'; /* 表选产品代码 */
export default {
  name: 'addEstimateModal',
  components: {
    // selectLicense
    // selectCPDM
  },
  mixins: [dictionary, authority],
  props: ['type', 'rowData'],
  data() {
    this.conf = { add: '保 存', edit: '修 改' };
    this.saveData = null;
    return {
      activeName: '维修项目',
      menus: this.createMenu(),
      lincenseSearchDialog: false,
      formList: this.createFormList(),
      repairList1: [],
      repairList2: [],
      labourAmount: 0,
      partAmount: 0,
      yhje: 0
      // visible2: false
    };
  },
  computed: {
    btnText() {
      return this.conf[this.type];
    }
  },
  mounted() {
    this.init();
    this.initSelect();
    this.personnel();
    this.initData();
  },
  methods: {
    createMenu() {
      let that = this;
      return [
        {
          title: '维修项目',
          path: 'repair/extension/estimateExtension/projectTable',
          params: {
            Tlist: [],
            isclear: false,
            code: '',
            price: 0,
            discount: null,
            labourPrice: null,
            isdisabled: false,
            orderStatus: null, // 是否是一车一单的数据
            repairType: null, // 维修类型,
            seriesId: null,
            brand: null, // 品牌
            repairTypeList: [] // 维修项目类型数组
          },
          on: {
            changeList(val) {},
            syncTablelist(val) {
              console.log(val, '维修项目！！！');
              if (val.length > 0) {
                that.repairList1 = val;
                that.labourAmount = 0;
                val.forEach(x => {
                  that.labourAmount += parseInt(x.LABOUR_AMOUNT);
                });
                that.JS();
              } else {
                that.repairList1 = [];
              }
              // that.assessData.maintainPro = val;
              // that.savelabourAmount();
            },
            changeClear(val) {
              that.menus[0].params.isclear = false;
            },
            delList(val) {
              console.log(val, '删除');
              let a = that.arr;
              that.arr = a.concat(val);
            }
          }
        },
        {
          title: '维修材料',
          path: 'repair/extension/estimateExtension/materialTable',
          params: {
            Tlist: [],
            isclear: false,
            projectData: [],
            code: '',
            discount: null,
            isdisabled: false,
            labourList: []
          },
          on: {
            changeList(val) {},
            syncTablelist(val) {
              console.log(val, '维修材料');
              if (val.length > 0) {
                that.partAmount = 0;
                that.repairList2 = val;
                val.forEach(x => {
                  that.partAmount += parseInt(x.PART_AMOUNT);
                });
                that.JS();
              } else {
                that.repairList2 = [];
              }
            },
            changeClear(val) {
              that.menus[1].params.isclear = false;
            },
            delList(val) {
              console.log(val, '删除');
              that.arrs = that.arrs.concat(val);
            }
          }
        }
      ];
    },
    // 初始化页面显示隐藏数据
    initData() {
      console.log(this.rowData, '+++++++++++++++++++++++++++++++++++++++' + this.type);
      if (this.type == 'add') {
        // 新建
        this.$nextTick(() => {
          this.formList.find(k => k.fieldName === 'REPAIR_STATUS').initialValue = '96381002';
        });
      } else if (this.type == 'edit') {
        // 编辑
        this.getEstimate();
      } else {
        // 明细
        this.getEstimate();
        this.formList.forEach(x => {
          x.disabled = true;
        });
        this.menus[0].params.isdisabled = true;
        this.menus[1].params.isdisabled = true;
      }
    },
    // 服务顾问下拉选
    async personnel() {
      let testDrive = { role: dictCode.SERVICE_CONSULTANT };
      let res5 = (await searchRoleByCode(testDrive)).data.map(x => ({ value: x.userId + '', text: x.employeeName }));
      this.formList.find(item => item.fieldName === 'SV_USER').itemList = res5;
      // this.formList.find(x => x.fieldName === 'CREATED_BY').itemList = (await getAllUser()).data.map(x => ({
      //   text: x.employeeName,
      //   value: x.userId + ''
      // }));
    },
    // 获取页面需要的数据
    async getEstimate() {
      let estimate = await getEstimateData({ EXT_NO: this.rowData.EXT_NO });
      let labour = await getLabourData({ EXT_NO: this.rowData.EXT_NO });
      let Part = await getPartData({ EXT_NO: this.rowData.EXT_NO });

      this.menus[0].params.Tlist = labour.data;
      this.menus[1].params.Tlist = Part.data;

      this.formList.forEach(x => {
        x.initialValue = estimate.data[x.fieldName];
      });
      this.menus[0].params.price = estimate.data['LABOUR_PRICE'] ? '' : 0;
    },

    init() {
      if (this.type === 'edit') {
        // 更新接口需要的记录 ID
        this.applyId = this.rowData.applyId;
        this.formList.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
        });
      }
    },
    createFormList() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '单据信息',
          style: {}
        },
        {
          type: 'INPUT',
          label: '延保估算单号',
          disabled: true,
          fieldName: 'EXT_NO'
          // rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },

        {
          type: 'DATE_TIME',
          label: '估算日期',
          fieldName: 'EXT_DATE',
          initialValue: moment().format('YYYY-MM-DD HH:mm:ss'),
          disabled: true
        },
        {
          type: 'SELECT',
          label: '维修状态',
          disabled: true,
          fieldName: 'REPAIR_STATUS',
          initialValue: '',
          itemList: this.createDictList('9638')
        },
        {
          type: 'INPUT',
          label: '底盘号',
          disabled: false,
          fieldName: 'VIN',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }],
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.openLicense()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '发动机号',
          disabled: false,
          fieldName: 'ENGINE_NO',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '牌照号',
          disabled: false,
          fieldName: 'PLATE_NO',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '行驶里程',
          fieldName: 'MILAGE',
          disabled: false,
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '车型',
          disabled: false,
          fieldName: 'MODEL_CODE',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '车系',
          disabled: true,
          fieldName: 'SERIES_CODE',
          itemList: [],
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'DATE',
          label: '生产日期',
          disabled: false,
          fieldName: 'PRODUCT_DATE',
          dateFormat: 'yyyy-MM-dd',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'DATE',
          label: '购车日期',
          disabled: false,
          fieldName: 'SALES_DATE',
          dateFormat: 'yyyy-MM-dd',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '服务顾问 ',
          disabled: false,
          fieldName: 'SV_USER',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }],
          itemList: []
        },
        {
          type: 'INPUT',
          label: '客户代码',
          disabled: true,
          fieldName: 'CUS_CODE',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '客户名称',
          disabled: true,
          fieldName: 'CUS_NAME',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '联系电话',
          disabled: true,
          fieldName: 'TELPHONE',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '故障描述',
          disabled: false,
          fieldName: 'FAULT_REMARKS',
          selfCols: 2,
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          disabled: true,
          fieldName: 'OWNER_CODE',
          rules: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '延保申请单号',
          disabled: true,
          fieldName: 'UP_EXT_NO'
        },
        {
          type: 'DATE',
          label: '延保申请日期',
          disabled: true,
          fieldName: 'UP_EXT_DATE'
        },
        {
          type: 'INPUT',
          label: '操作员',
          disabled: true,
          fieldName: 'CREATED_BY',
          initialValue: getUser()
        },
        {
          type: 'INPUT',
          label: '上传状态',
          disabled: true,
          fieldName: 'UP_STATUS',
          initialValue: '0'
        },
        {
          type: 'INPUT',
          label: '上传状态描述',
          disabled: true,
          fieldName: 'UP_REMARKS',
          initialValue: '未上传'
        },
        {
          type: 'DATE',
          label: '上传日期',
          disabled: true,
          fieldName: 'UP_DATE'
        },
        {
          type: 'INPUT',
          label: '应收工时费',
          disabled: true,
          fieldName: 'LABOUR_AMOUNT'
        },
        {
          type: 'INPUT',
          label: '应收材料费',
          disabled: true,
          fieldName: 'REPAIR_PART_AMOUNT'
        },
        {
          type: 'INPUT',
          label: '应收合计',
          disabled: true,
          fieldName: 'carModer573'
        },
        {
          type: 'INPUT_NUMBER',
          label: '优惠金额',
          disabled: false,
          fieldName: 'DERATE_AMOUNT',
          change: val => {
            if (val) {
              this.yhje = 0;
            } else {
              this.yhje = val;
            }
            this.JS();
          }
        },
        {
          type: 'INPUT',
          label: '优惠后合计',
          disabled: true,
          fieldName: 'carModer572'
        },
        {
          type: 'INPUT',
          label: '备注',
          disabled: true,
          fieldName: 'REMARKS'
        },
        {
          type: 'SELECT',
          label: '工时单价 ',
          disabled: false,
          fieldName: 'LABOUR_PRICE',
          itemList: [],
          change: val => {
            this.menus[0].params.price = val;
          }
        },
        {
          type: 'CHECKBOX',
          label: '是否所有',
          fieldName: 'checkIsChooseWorkHourcePrice',
          selfCols: 0.4,
          change: val => {
            this.handleSeriesAndWorkHourcePrice(val);
          }
        }
      ];
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    async saveDialog() {
      this.saveData = null;
      this.$refs.formPanel.SUBMIT_FORM();
      // alert(JSON.stringify(this.saveData))
      if (this.saveData) {
        this.saveData = Object.assign(
          {},
          this.saveData,
          { labour: this.repairList1.length > 0 ? this.repairList1 : this.menus[0].params.Tlist },
          { part: this.repairList2.length > 0 ? this.repairList2 : this.menus[1].params.Tlist }
        );
        let res = await saveEstimate(this.saveData);
        if (res.resultCode === 200) {
          this.$notify({
            title: '提示信息',
            message: '保存成功！',
            type: 'success'
          });
          this.closeDialog('refresh');
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请填写必填项!'
        });
      }
    },

    // 是否所有
    async handleSeriesAndWorkHourcePrice(val) {
      if (val == 1) {
        const gsdj = await getGsdjSelect();
        this.formList.find(x => x.fieldName === 'LABOUR_PRICE').itemList = gsdj.data.map(x => ({ value: x.LABOUR_PRICE + '', text: `${x.LABOUR_PRICE}` }));
      }
    },
    // 下拉选
    async initSelect() {
      let series = this.formList.find(item => item.fieldName === 'SERIES_CODE').initialValue;
      const res1 = await getSeries();
      this.formList.find(item => item.fieldName === 'SERIES_CODE').itemList = res1.data.map(x => ({ text: x.SERIES_NAME, value: x.SERIES_ID + '' }));
      let res2 = await getModelAllListOEM();
      console.log('车系', res1.data, '车型', res2.data);
      this.formList.find(item => item.fieldName === 'MODEL_CODE').itemList = res2.data.map(x => ({ text: x.modelName, value: x.modelId + '' }));
      let params = { seriesId: series };
      const gsdj = await getGsdjSelect(params);
      this.formList.find(x => x.fieldName === 'LABOUR_PRICE').itemList = gsdj.data.map(x => ({ value: x.LABOUR_PRICE + '', text: `${x.LABOUR_PRICE}` }));
    },
    // 车牌号  弹出框
    async openLicense() {
      this.lincenseSearchDialog = true;
    },
    // VIN选择确认方法
    async getSelectLicense(arr) {
      this.lincenseSearchDialog = false;
      if (!arr.length) {
        return;
      }
      let obj = arr[0];
      if (obj.BRAND) {
        let data = Object.assign(
          {},

          { brand: obj.BRAND }
        );
        let res = await getseriessdictList(data);
        this.formList.find(item => item.fieldName === 'SERIES_CODE').itemList = res.data.map(x => ({ text: x.SERIES_NAME, value: x.SERIES_CODE }));
      }
      if (obj.BRAND && obj.SERIES) {
        let brand = obj.BRAND;
        let series = obj.SERIES;
        let data = Object.assign(
          {},

          { brand: brand, series: series }
        );
        let res = await getmodelsdictList(data);
        this.formList.find(item => item.fieldName === 'MODEL_CODE').itemList = res.data.map(x => ({ text: x.MODEL_NAME, value: x.MODEL_CODE }));
      }
      let params = { seriesId: obj.SERIES };
      const gsdj = await getGsdjSelect(params);
      this.formList.find(x => x.fieldName === 'LABOUR_PRICE').itemList = gsdj.data.map(x => ({ value: x.LABOUR_PRICE + '', text: `${x.LABOUR_PRICE}` }));

      for (let i in obj) {
        obj[i] = obj[i] === null ? '' : obj[i];
        for (let j = 0; j < this.formList.length; j++) {
          if (i == this.formList[j].fieldName) {
            this.formList[j].initialValue = obj[i];
          }
          if (i == 'LICENSE') {
            this.formList.find(item => item.fieldName === 'PLATE_NO').initialValue = obj[i];
          }
          if (i == 'MILEAGE') {
            this.formList.find(item => item.fieldName === 'MILAGE').initialValue = obj[i];
          }
          if (i == 'SERIES') {
            this.formList.find(item => item.fieldName === 'SERIES_CODE').initialValue = obj[i];
          }
          if (i == 'MODEL') {
            this.formList.find(item => item.fieldName === 'MODEL_CODE').initialValue = obj[i];
          }
          if (i == 'OWNER_NO') {
            this.formList.find(item => item.fieldName === 'CUS_CODE').initialValue = obj[i];
          }
          if (i == 'OWNER_NAME') {
            this.formList.find(item => item.fieldName === 'CUS_NAME').initialValue = obj[i];
          }
          if (i == 'DELIVERER_MOBILE') {
            this.formList.find(item => item.fieldName === 'TELPHONE').initialValue = obj[i];
          }
          if (i == 'SERVICE_ADVISOR') {
            this.formList.find(item => item.fieldName === 'SV_USER').initialValue = obj[i];
          }
        }
      }
    },
    JS() {
      this.$nextTick(() => {
        this.formList.find(item => item.fieldName === 'LABOUR_AMOUNT').initialValue = this.labourAmount;
        this.formList.find(item => item.fieldName === 'REPAIR_PART_AMOUNT').initialValue = this.partAmount;
        this.formList.find(item => item.fieldName === 'carModer573').initialValue = this.labourAmount + this.partAmount;
        this.formList.find(item => item.fieldName === 'carModer572').initialValue = this.labourAmount + this.partAmount - this.yhje;
      });
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    }
  }
};
</script>

<style lang="less" scoped></style>
